import requests
import os
import json
from utils.logger import setup_logger

def load_config():
    config_path = os.path.join(os.path.dirname(__file__), "../config/config.json")
    with open(config_path, "r") as f:
        return json.load(f)

config = load_config()

logger = setup_logger()

class APIClient:
    def __init__(self, protocol, environment, base_url):
        """
        初始化 APIClient
        :param protocol: 请求协议（http or https）
        :param environment: internet or intranet
        :param base_url: 基础url地址（例如 httpbin.org）
        """
        self.environment = environment
        self.protocol = protocol
        self.base_url = base_url

        # 根据协议和环境配置生成base_url
        self.base_url = f"{self.protocol}://{self.base_url}"

        # 默认的请求头
        self.headers = config["default_headers"]

    def get(self, endpoint, headers=None, auth=None, params=None):
        url = f"{self.base_url}{endpoint}"
        # 合并默认和自定义的headers
        headers = self.headers | (headers or {})
        logger.info(f"Sending GET request to {url} with params: {params}")
        response = requests.get(url, headers=headers, auth=auth, params=params)
        return response

    def post(self, endpoint, headers=None, auth=None, params=None, data=None):
        url = f"{self.base_url}{endpoint}"
        headers = self.headers | (headers or {})
        logger.info(f"Sending POST request to {url} with data: {data} and json: {json}")
        response = requests.post(url, headers=headers, auth=auth, params=params, data=data)
        return response

    def put(self, endpoint, headers=None, auth=None, data=None):
        url = f"{self.base_url}{endpoint}"
        headers = self.headers | (headers or {})
        logger.info(f"Sending PUT request to {url} with data: {data} and json: {json}")
        response = requests.put(url, headers=headers, auth=auth, data=data)
        return response

    def delete(self, endpoint, headers=None, auth=None, params=None):
        url = f"{self.base_url}{endpoint}"
        headers = self.headers | (headers or {})
        logger.info(f"Sending DELETE request to {url} with params: {params}")
        response = requests.delete(url, headers=headers, auth=auth, params=params)
        return response

    def patch(self, endpoint, headers=None, auth=None, data=None):
        url = f"{self.base_url}{endpoint}"
        headers = self.headers | (headers or {})
        logger.info(f"Sending PATCH request to {url} with data: {data} and json: {json}")
        response = requests.patch(url, headers=headers, auth=auth)
        return response